<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="search-box">
      <input class="search-input" placeholder="搜索城市名/拼音" v-model="searchQuery" />
    </view>

    <!-- 定位城市 -->
    <view class="location-city">
		<text class="section-title">定位城市</text>
		<view class="city-list">
		  <text style="background-color: #CACCFF;">{{ locatedCity }}</text>
		</view>
    </view>

    <!-- 热门城市 -->
    <view class="hot-cities">
      <text class="section-title">热门城市</text>
      <view class="city-list">
        <text v-for="city in hotCities" :key="city" @click="selectCity(city)">{{ city }}</text>
      </view>
    </view>

    <!-- 按字母 A-Z 排列的城市列表 -->
        <view class="all-cities">
          <view v-for="group in filteredCityGroups" :key="group.initial">
            <text class="section-title">{{ group.initial }}</text>
            <view class="city-list">
              <text
                v-for="city in group.list"
                :key="city.code"
                @click="selectCity(city.name)"
              >
                {{ city.name }}
              </text>
            </view>
          </view>
        </view>
  </view>
</template>

<script>
	import { cities } from "@/components/cities/cities/cities.js"; // 导入城市数据
export default {
  data() {
    return {
      locatedCity: '佛山',
      hotCities: ['北京', '上海', '广州'],
	  cities: cities, // 导入的城市数据
      searchQuery: ''
    };
  },
  computed: {
      // 根据搜索框内容过滤城市列表
      filteredCityGroups() {
        if (!this.searchQuery) {
          return this.cities; // 如果没有搜索内容，返回全部城市
        }
        return this.cities
          .map((group) => ({
            initial: group.initial,
            list: group.list.filter((city) =>
              city.name.includes(this.searchQuery) ||
              city.pinyin.toLowerCase().includes(this.searchQuery.toLowerCase())
            ),
          }))
          .filter((group) => group.list.length > 0); // 过滤掉没有数据的字母组
      },
    },
  methods: {
    selectCity(city) {
      // 选择城市后返回上一个页面并更新选中的城市
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];
      prevPage.setData({
        selectedCity: city
      });
      uni.navigateBack();
    }
  }
};
</script>

<style>
.container {
  height: 100vh;
  padding: 13px;
  background-color: #fdfdfd;
}

.search-box {
  width: 355px;
  height: 40px;
  display: flex;
  align-items: center;
  background-color: #f6f7f8;
  border-radius: 32px;
  padding: 10px;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  border-radius: 4px;
}

.location-city {
  margin-bottom: 20px;
}

.section-title {
  font-weight: bold;
  display: block;
  margin-bottom: 10px;
}

.city-list {
  display: flex;
  flex-wrap: wrap;
}

.city-list text {
	width: 109px;
	height: 30px;
	line-height: 30px;
  border-radius: 4px;
  background: #ECECEC;
  text-align: center;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.city-list text:nth-child(3n) {
  margin-right: 0;
  }
</style>